package com.huaxin.device.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.huaxin.device.dto.enums.AlarmType;
import com.huaxin.device.models.AlarmState;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Service
public class AlarmStateService {

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ObjectMapper objectMapper;

    private static final String ALARM_STATE_PREFIX = "alarm:state:";

    // 构建 Redis Key
    private String buildKey(String deviceId, AlarmType alarmType) {
        return ALARM_STATE_PREFIX + deviceId + ":" + alarmType.getCode();
    }

    // 获取状态
    public AlarmState getState(String deviceId, AlarmType alarmType) {
        String key = buildKey(deviceId, alarmType);
        String json = redisTemplate.opsForValue().get(key);
        if (json == null) return null;
        try {
            return objectMapper.readValue(json, AlarmState.class);
        } catch (Exception e) {
            return null;
        }
    }

    // 保存状态
    public void saveState(String deviceId, AlarmType alarmType, AlarmState state) {
        String key = buildKey(deviceId, alarmType);
        try {
            String json = objectMapper.writeValueAsString(state);
            // 可设置过期时间，比如 7 天
            redisTemplate.opsForValue().set(key, json, 7, TimeUnit.DAYS);
        } catch (Exception e) {
            // log.error("保存报警状态失败", e);
        }
    }

    // 清除状态（如设备离线）
    public void clearState(String deviceId, AlarmType alarmType) {
        String key = buildKey(deviceId, alarmType);
        redisTemplate.delete(key);
    }
}
